<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 登录接口
 */
class Auth extends Api
{
    protected $noNeedLogin = ['login', 'wxlogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 小程序登录
     */
    public function wxlogin()
    {
        $is_simulation = request()->param('is_simulation');
        $inviter_id = request()->param('inviter_id');
        // 小程序端得到用户码，发给微信换取openid
        $code = request()->param('code');
        if ($is_simulation) {
            $ret = $this->auth->wx_login($code, $inviter_id);
        } else {
            $wxapp_id = Config::get('site.wxapp_id');
            $wxapp_secret = Config::get('site.wxapp_secret');
            if (!$wxapp_id || !$wxapp_secret) {
                $this->error('还未开通小程序');
            }
            // 初始化小程序接口SDK
            $WxappApi = Factory::miniProgram([
                'app_id' => $wxapp_id,
                'secret' => $wxapp_secret,
                //'token'     => 'easywechat',
                'log' => [
                    'level' => 'debug',
                    'file' => '/tmp/easywechat.log',
                ],
                // ...
            ]);

            if (empty($code)) {
                $this->error('缺少参数');
            }
            $oauth = $WxappApi->auth->session($code);
            if (empty($oauth['openid'])) {
                $this->error('微信授权登录失败。errcode:' . $oauth['errcode'] . 'errmsg:' . $oauth['errmsg']);
            }
            //消息解密
//            $decryptedData = $WxappApi->encryptor->decryptData($session, $iv, $encryptedData);
            // 根据 oauth['openid'] 在应用中获取用户信息，如果没有则自动创建
            $ret = $this->auth->wx_login($oauth['openid'], $inviter_id);
        }
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取手机号
     * @return void
     */
    public function getPhone()
    {
        // 小程序端得到用户码，发给微信换取openid
        $code = request()->param('code');
        $session = request()->param('session');
        $iv = request()->param('iv');
        $encryptedData = request()->param('encryptedData');
        $wxapp_id = Config::get('site.wxapp_id');
        $wxapp_secret = Config::get('site.wxapp_secret');
        if (!$wxapp_id || !$wxapp_secret) {
            $this->error('还未开通小程序');
        }
        // 初始化小程序接口SDK
        $WxappApi = Factory::miniProgram([
            'app_id' => $wxapp_id,
            'secret' => $wxapp_secret,
            //'token'     => 'easywechat',
            'log' => [
                'level' => 'debug',
                'file' => '/tmp/easywechat.log',
            ],
            // ...
        ]);
//        if (empty($code)) {
//            $this->error('缺少参数');
//        }
//        $oauth = $WxappApi->auth->session($code);
//        if (empty($oauth['openid'])) {
//            $this->error('微信授权登录失败。errcode:' . $oauth['errcode'] . 'errmsg:' . $oauth['errmsg']);
//        }
        //消息解密
        $decryptedData = $WxappApi->encryptor->decryptData($session, $iv, $encryptedData);
        $user = $this->auth->getUser();
        if($user->mobile > 0){
            $this->success(__('成功'), $user);
        }else{
            db('user')->where('id',$user->id)->update([
                'mobile' => $decryptedData
            ]);
        }
    }
}
